package org.realogic.cfm.authenticate;

import java.io.Serializable;
import java.util.regex.Pattern;

public class IP implements Serializable {
	private static final long serialVersionUID = -1340593628926401945L;

	private static final String re = "(\\\\d{1,2})";
	private String[] ps;

	public IP(String ip) {
		this.ps = ip.split("[.]");
		if ((this.ps == null) || (this.ps.length != 4))
			throw new IllegalArgumentException("IP地址不可用: " + ip);
	}

	public boolean matching(String ip) {
		String[] _ps = ip.split("[.]");
		if ((_ps == null) || (_ps.length != 4)) {
			throw new IllegalArgumentException("IP地址不可用: " + ip);
		}

		for (int i = 0; i < 4; i++) {
			if (!matchingP(_ps[i], i)) {
				return false;
			}
		}

		return true;
	}

	private boolean matchingP(String p, int index) {
		if (("*".equals(this.ps[index])) || (p.equals(this.ps[index]))) {
			return true;
		}
		String rep = this.ps[index].replaceAll("[*]", re);
		return Pattern.matches(rep, p);
	}
}